package inits

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
	"video-service/basic/config"
	"video-service/basic/global"
	"video-service/internal/model"
)

var once sync.Once

func InitMysql() {
	once.Do(func() {
		var err error
		mysqlConfig := config.Config.Mysql
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True",
			mysqlConfig.User,
			mysqlConfig.Password,
			mysqlConfig.Host,
			mysqlConfig.Port,
			mysqlConfig.Database,
		)
		global.DB, err = gorm.Open(mysql.Open(dsn))
		if err != nil {
			panic(err)
		}
		fmt.Println("数据库连接成功")
		err = global.DB.AutoMigrate(&model.Video{}, &model.VideoEpisode{}, &model.PlayLog{})
		if err != nil {
			panic(err)
		}
		fmt.Println("数据表迁移成功")
		db, err := global.DB.DB()
		if err != nil {
			panic(err)
		}
		fmt.Println("数据池连接成功")
		db.SetMaxIdleConns(10)
		db.SetMaxOpenConns(100)

	})
}
